from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import requests
import re

app = Flask(__name__)
app.config.from_pyfile('config.py')
CORS(app)  # 允许跨域请求
db = SQLAlchemy(app)

# 导入模型（必须在db初始化之后）
from models import Location, Book

API_KEY="ae1718d4587744b0b79f940fbef69e77"

@app.route('/api/books', methods=['GET'])
def get_books():
    search = request.args.get('search', '')
    query = Book.query
    if search:
        query = query.filter(Book.title.contains(search) | 
                            Book.authors.contains(search) |
                            Book.isbn.contains(search))
    books = query.order_by(Book.add_time.desc()).all()
    return jsonify([{
        'id': book.id,
        'isbn': book.isbn,
        'title': book.title,
        'authors': book.authors,
        'publisher': book.publisher,
        'price': book.price,
        'location_code': book.location_code,
        'add_time': book.add_time.strftime('%Y-%m-%d %H:%M')
    } for book in books])

# 位置编码格式验证
def validate_location_code(code):
    pattern = r'^[A-Z]\d{2}-(SH|BX)\d{2}$'  # 示例格式：A01-SH01
    return re.match(pattern, code) is not None

@app.route('/api/books', methods=['POST'])
def add_book():
    data = request.json
    
    # 增加位置验证
    if not validate_location_code(data.get('location_code', '')):
        return jsonify({'error': '位置编码格式错误'}), 400
    
    # 检查位置是否还有空间
    loc=Location.query.filter_by(code=data["location_code"]).first()
    if Book.query.filter_by(location_code=loc.code).count()>=loc.capacity-1:
        return jsonify({"error": "No capacity for this location."}), 400

    if not re.match(r'^\d{10}(\d{3})?$', data['isbn']):
        return jsonify({'error': 'Invalid ISBN format'}), 400
    
    if Book.query.filter_by(isbn=data['isbn']).first():
        return jsonify({'error': 'Book already exists'}), 409

    # 调用API
    try:
        res = requests.get(f"http://data.isbn.work/openApi/getInfoByIsbn?isbn={data['isbn']}&appKey={API_KEY}")
        book_data = res.json()["data"]
        new_book = Book(
            isbn=data['isbn'],
            title=book_data.get('bookName', '未知'),
            authors=book_data.get('author', []),
            publisher=book_data.get('press', '未知'),
            publish_date=book_data.get('pressDate', ''),
            pages=book_data.get('pages', 0),
            price=float(book_data.get('price', ''))/100,
            summary=book_data.get('bookDesc', ''),
            location_code=data['location_code']
        )
        db.session.add(new_book)
        db.session.commit()
        return jsonify({'message': 'Book added successfully'}), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
    book = Book.query.get(book_id)
    if not book:
        return jsonify({'error': '图书不存在'}), 404
    
    try:
        db.session.delete(book)
        db.session.commit()
        return jsonify({'message': '图书删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
    
# 获取所有位置
@app.route('/api/locations', methods=['GET'])
def get_locations():
    locations = Location.query.all()
    return jsonify([{
        'code': loc.code,
        'type': loc.type,
        'description': loc.description,
        'current_count': Book.query.filter_by(location_code=loc.code).count()
    } for loc in locations])

# 新增位置
@app.route('/api/locations', methods=['POST'])
def add_location():
    data = request.json
    # 验证编码唯一性
    if Location.query.get(data['code']):
        return jsonify({'error': '位置编码已存在'}), 400
    
    new_loc = Location(**data)
    db.session.add(new_loc)
    db.session.commit()
    return jsonify({'message': '位置添加成功'}), 201

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=5000)